import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'models/post_model.dart';
import '../../../common/api/activity_api.dart';
import '../../../common/api/comment_api.dart';
import '../../../common/api/user_api.dart';
import '../../../common/models/index.dart';
import '../../../common/services/user_service.dart'; // 🔑 用户服务
import 'dart:developer' as developer;
import 'dart:async';

class PlaysController extends GetxController
    with GetSingleTickerProviderStateMixin {
  PlaysController();

  // TabController for managing tabs
  late TabController tabController;

  // PageController for managing page transitions
  late PageController pageController;

  // 当前选中的标签索引 (for background color)
  final RxInt currentTabIndex = 0.obs;

  // 标签名称列表
  final List<String> tabNames = ['评论', '活动', '我的发布'];

  // 数据列表
  final RxList<PostModel> commentPosts = <PostModel>[].obs;
  final RxList<PostModel> activityPosts = <PostModel>[].obs;
  final RxList<PostModel> myPublishPosts = <PostModel>[].obs;
  final RxList<PostModel> historicalActivityPosts = <PostModel>[].obs;
  // 添加我的评论数据列表（PostModel格式，用于显示）
  final RxList<PostModel> myCommentsPosts = <PostModel>[].obs;
  // 添加我的视频和我的参与数据列表
  final RxList<PostModel> myVideosPosts = <PostModel>[].obs;
  final RxList<PostModel> myParticipationsPosts = <PostModel>[].obs;

  // 刷新控制器
  late RefreshController activityRefreshController;
  late RefreshController commentRefreshController;
  
  // 我的发布页面相关刷新控制器
  late RefreshController myHistoryRefreshController;
  late RefreshController myCommentsRefreshController;
  late RefreshController myParticipationRefreshController;
  late RefreshController activityManagementRefreshController;

  // 活动数据加载状态
  final RxBool isLoadingActivities = false.obs;
  final RxBool isRefreshingActivities = false.obs;

  // 评论数据加载状态
  final RxBool isLoadingComments = false.obs;
  final RxBool isRefreshingComments = false.obs;

  // 活动分页参数
  int activityCurrentPage = 1;
  final int activityPageSize = 10;
  final RxBool hasMoreActivities = true.obs;

  // 评论分页参数
  int commentCurrentPage = 1;
  final int commentPageSize = 10;
  final RxBool hasMoreComments = true.obs;

  // 默认经纬度（北京）
  static const double defaultLatitude = 39.915;
  static const double defaultLongitude = 116.404;
  static const double defaultRadius = 50.0;
  
  // 用户发布内容相关状态
  final RxBool isLoadingUserContent = false.obs;
  final RxList<ActivityData> myActivities = <ActivityData>[].obs;
  final RxList<ActivityData> myEndedActivities = <ActivityData>[].obs;
  final RxList<UserComment> myComments = <UserComment>[].obs;
  
  // 当前用户ID（从UserService动态获取）
  final RxInt currentUserId = 0.obs;

  // 🔥 新增：防抖定时器
  Timer? _activityDebounceTimer;
  Timer? _commentDebounceTimer;

  // 🔥 新增：去重处理的辅助方法
  /// 活动数据去重方法
  void _addUniqueActivities(List<PostModel> newActivities, {bool isRefresh = false}) {
    if (isRefresh) {
      activityPosts.clear();
      activityPosts.addAll(newActivities);
      developer.log('🔄 活动数据刷新: ${newActivities.length}个');
    } else {
      // 获取现有ID集合
      final existingIds = activityPosts.map((post) => post.id).toSet();
      
      // 过滤重复数据
      final uniqueActivities = newActivities.where((post) => 
        !existingIds.contains(post.id)).toList();
      
      activityPosts.addAll(uniqueActivities);
      developer.log('🔍 活动去重处理: 新增${newActivities.length}个，去重后添加${uniqueActivities.length}个');
    }
  }

  /// 评论数据去重方法  
  void _addUniqueComments(List<PostModel> newComments, {bool isRefresh = false}) {
    if (isRefresh) {
      commentPosts.clear();
      commentPosts.addAll(newComments);
      developer.log('🔄 评论数据刷新: ${newComments.length}个');
    } else {
      final existingIds = commentPosts.map((post) => post.id).toSet();
      final uniqueComments = newComments.where((post) => 
        !existingIds.contains(post.id)).toList();
      
      commentPosts.addAll(uniqueComments);
      developer.log('🔍 评论去重处理: 新增${newComments.length}个，去重后添加${uniqueComments.length}个');
    }
  }

  // 头像URL数据
  final List<String> avatarUrls = [
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_1.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_2.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_3.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_4.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_5.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_6.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_7.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_8.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_9.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_10.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_11.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_12.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_13.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_14.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_15.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_16.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_17.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_18.webp',
  ];

  // 用户酒吧照片URL数据
  final List<List<String>> barPhotoUrls = [
    [
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/11.jpg',
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/12.jpg',
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/13.jpg',
    ],
    [
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/21.jpg',
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/22.jpg',
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/23.jpg',
    ],
    [
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/31.jpg',
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/32.jpg',
      'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/33.jpg',
    ],
  ];

  // 文案配图URL数据
  final List<String> artWorkUrls = [
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_154f5afcc73ab7814a745378c6dd2846_edit_391954352758421.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_06409c288f6c65c4f600bddf9283602f_edit_391871265051142.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_0e5b4a2b28ed3de4b0bd82dbf7c6903d_edit_391867197811038.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_0f12f2ab2759993eafd5c0dd836ad67d_edit_391959430881857.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_12c336fd9ed7524ebe87caa51e44ec8d.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_12d5f192fb067ace679599a7bfc52b6e_edit_391820114051670.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_b105a7255d8bf0471c21610206ae9db7_edit_391922025174051.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_be989e23a750abff0d49f15d593d659f_edit_391842228905313.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_bf3372c16f74e2319d819cd8d0249598_edit_391838237835522.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_bfea1f27dd623b7795fc0ec10ab955d9_edit_391834057361043.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_c09e38f3a790012f67d6c21b7b648b68_edit_391768809149074.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_c2cfd9ded965c38680f00a21a01386f4_edit_391916608718322.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_cdec2b9dcd00187206c05ebebd34b362_edit_391829318571981.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_d5e6dc5448275fdaee80ce22ae7bab3c_edit_391989959571436.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_d93455220d9d532bd7b6fae5ce5b2fb9_edit_391824984901670.png',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_dbbd0aa66f4e22dd88e386835e890715_edit_391764026560533.png',
  ];

  _initData() {
    // 获取真实活动数据
    loadRealActivityData();
    // 获取真实评论数据
    loadRealCommentData();
    // 获取用户发布的内容
    loadUserContent();
    // 获取用户完整内容（评论+参与活动）
    loadUserFullContent();
    update(["plays"]);
  }

  /// 获取真实活动数据
  Future<void> loadRealActivityData() async {
    if (isLoadingActivities.value) return;
    
    try {
      isLoadingActivities.value = true;


      final response = await ActivityApi.getNearbyActivities(
        latitude: defaultLatitude,
        longitude: defaultLongitude,
        radius: defaultRadius,
        limit: 20, // 获取20个活动
      );

      if (response.isSuccess) {
        // 将ActivityData转换为PostModel
        final realActivityPosts = response.data.map((activityData) => 
          _convertActivityDataToPostModel(activityData)).toList();
        
        // 🔥 使用去重方法更新真实数据
        _addUniqueActivities(realActivityPosts, isRefresh: true);
        
        // 🎯 添加时间排序，确保与下拉刷新保持一致
        _sortActivitiesByTime();
      }
    } catch (e) {

      // 发生异常时，保留原有的模拟数据
    } finally {
      isLoadingActivities.value = false;
    }
  }

  /// 刷新活动数据（下拉刷新用）
  Future<void> refreshActivityData() async {
    if (isRefreshingActivities.value) return;
    
    try {
      isRefreshingActivities.value = true;


      final response = await ActivityApi.getNearbyActivities(
        latitude: defaultLatitude,
        longitude: defaultLongitude,
        radius: defaultRadius,
        limit: 20,
      );

      if (response.isSuccess) {

        
        final realActivityPosts = response.data.map((activityData) => 
          _convertActivityDataToPostModel(activityData)).toList();
        
        activityPosts.clear();
        activityPosts.addAll(realActivityPosts);
        
        // 🎯 按时间排序，确保新发布的活动在第一位
        _sortActivitiesByTime();
      } else {

      }
    } catch (e) {

    } finally {
      isRefreshingActivities.value = false;
    }
  }

  /// 🔄 活动下拉刷新
  Future<void> onActivityRefresh() async {
    // 🔥 防抖处理：取消之前的定时器
    _activityDebounceTimer?.cancel();
    
    try {
      // 重置分页参数
      activityCurrentPage = 1;
      hasMoreActivities.value = true;
      
      await loadActivityData(isRefresh: true);
      
      activityRefreshController.refreshCompleted();
      
    } catch (e) {
      activityRefreshController.refreshFailed();
      developer.log('💥 活动刷新失败: $e');
    }
  }

  /// ⬆️ 活动上拉加载更多
  Future<void> onActivityLoading() async {
    // 🔥 防抖处理：防止重复加载
    if (isLoadingActivities.value) {
      developer.log('⚠️ 活动正在加载中，跳过重复请求');
      return;
    }
    
    try {
      if (!hasMoreActivities.value) {
        activityRefreshController.loadNoData();
        return;
      }
      
      activityCurrentPage++;
      
      await loadActivityData(isRefresh: false);
      
      if (hasMoreActivities.value) {
        activityRefreshController.loadComplete();
      } else {
        activityRefreshController.loadNoData();
      }
      
    } catch (e) {
      activityCurrentPage--; // 失败时回退页码
      activityRefreshController.loadFailed();
      developer.log('💥 活动加载失败: $e');
    }
  }

  /// 📡 通用活动数据加载方法
  Future<void> loadActivityData({required bool isRefresh}) async {
    try {
      if (isRefresh) {
        isLoadingActivities.value = true;
      }
      

      
      final response = await ActivityApi.getNearbyActivities(
        latitude: defaultLatitude,
        longitude: defaultLongitude,
        radius: defaultRadius,
        limit: activityPageSize,
        page: activityCurrentPage, // 🔥 关键：传递分页参数
      );

      if (response.isSuccess) {
        
        // 将ActivityData转换为PostModel
        final realActivityPosts = response.data.map((activityData) => 
          _convertActivityDataToPostModel(activityData)).toList();
        
        // 🔥 使用去重方法处理数据
        _addUniqueActivities(realActivityPosts, isRefresh: isRefresh);
        
        // 🎯 每次加载后都进行时间排序，确保最新活动在顶部
        _sortActivitiesByTime();
        
        // 🔍 检查是否还有更多数据
        final currentPageSize = realActivityPosts.length;
        hasMoreActivities.value = currentPageSize >= activityPageSize;
        
        // 如果当前页返回的数据少于pageSize，说明没有更多数据了
        if (currentPageSize < activityPageSize) {
          hasMoreActivities.value = false;

        }
        

      } else {


      }
    } catch (e) {


    } finally {
      if (isRefresh) {
        isLoadingActivities.value = false;
      }
    }
  }

  /// 将ActivityData转换为PostModel
  PostModel _convertActivityDataToPostModel(ActivityData activityData) {
    return PostModel(
      id: 'real_activity_${activityData.activityId}',
      title: activityData.activityTitle,
      content: activityData.activityDetails.isNotEmpty 
          ? activityData.activityDetails 
          : '暂无详细描述',
      authorName: activityData.publisherNickname,
      authorAvatar: activityData.publisherAvatar, // 🔥 修复：直接使用发布者头像，不使用默认头像
      authorSignature: activityData.publisherSignature.isNotEmpty 
          ? activityData.publisherSignature 
          : '这个人很懒，什么都没留下',
      images: activityData.activityImages.isNotEmpty 
          ? activityData.activityImages 
          : [artWorkUrls[activityData.activityId % artWorkUrls.length]], // 如果没有图片，使用默认图片
      shoppingImages: [], // 活动不需要购物小票
      likeCount: 0, // ActivityData中没有点赞数，设为0
      commentCount: activityData.activityCurrentParticipants,
      timeAgo: activityData.participantDescription, // 显示参与人数信息
      type: PostType.activity,
      paymentType: _getPaymentTypeFromActivityType(activityData.activityType),
      authorId: activityData.publisherId, // 🔥 添加发布者ID
      activityPublishTime: activityData.activityPublishTime, // 🔥 保存活动开始时间（与MyApplication2一致）
      publishTime: activityData.activityPublishTime, // 🔥 保持兼容性
      timestamp: activityData.activityId, // 🔥 使用活动ID作为时间戳（较大的ID通常是较新的）
      extraData: activityData.extraData != null 
          ? ActivityExtraData.fromJson(activityData.extraData!) 
          : null, // 🔥 传递extraData
      // 🎯 活动专用字段
      maxParticipants: activityData.activityMaxParticipants, // ✅ 最大参与人数
      currentParticipants: activityData.activityCurrentParticipants, // ✅ 当前参与人数
      location: activityData.activityLocation.isNotEmpty  // ✅ 修复位置信息映射
          ? activityData.activityLocation 
          : null,
      latitude: activityData.latitude, // ✅ 活动纬度
      longitude: activityData.longitude, // ✅ 活动经度
      activityType: activityData.activityType, // ✅ 活动类型
      activityTags: activityData.activityTags, // ✅ 活动标签
    );
  }

  /// 根据活动类型获取支付方式
  String _getPaymentTypeFromActivityType(List<String> activityTypes) {
    developer.log('🔍 支付方式转换: activityTypes = $activityTypes');
    
    if (activityTypes.isEmpty) {
      developer.log('⚠️ 活动类型为空，返回默认值: 双方商议');
      return '双方商议'; // 空列表时返回默认值
    }
    
    // 直接使用第一个元素，因为API返回的activityType就是支付方式
    final firstType = activityTypes.first;
    developer.log('📝 第一个类型: "$firstType"');
    
    // 支持的支付方式: "AA", "我买单", "双方商议"
    if (firstType == 'AA' || firstType == '我买单' || firstType == '双方商议') {
      developer.log('✅ 直接匹配支付方式: $firstType');
      return firstType;
    }
    
    // 如果不是标准的支付方式，则根据内容推断
    if (firstType.contains('AA') || firstType.contains('聚餐')) {
      developer.log('🔍 推断为AA: $firstType');
      return 'AA';
    } else if (firstType.contains('我买单') || firstType.contains('运动') || firstType.contains('学习')) {
      developer.log('🔍 推断为我买单: $firstType');
      return '我买单';
    } else {
      developer.log('🔍 推断为双方商议: $firstType');
      return '双方商议';
    }
  }

  /// 获取真实评论数据
  Future<void> loadRealCommentData() async {
    if (isLoadingComments.value) return;
    
    try {
      isLoadingComments.value = true;
      
      // 🔥 重置分页参数，确保首次加载时状态正确
      commentCurrentPage = 1;
      hasMoreComments.value = true;

      final response = await CommentApi.getNearbyComments(
        latitude: defaultLatitude,
        longitude: defaultLongitude,
        radius: defaultRadius,
        limit: 20, // 获取20个评论
      );

      if (response.isSuccess) {
        // 将CommentData转换为PostModel
        final realCommentPosts = response.data.map((commentData) => 
          _convertCommentDataToPostModel(commentData)).toList();
        
        // 🔥 使用去重方法更新真实数据
        _addUniqueComments(realCommentPosts, isRefresh: true);
        
        // 🎯 添加时间排序，确保与下拉刷新保持一致
        _sortCommentsByTime();
        
        // 🔥 确保RefreshController处于正确状态
        try {
          if (commentRefreshController.footerStatus == LoadStatus.noMore) {
            commentRefreshController.resetNoData();
          }
          developer.log('🔄 首次加载评论数据完成，RefreshController状态正常');
        } catch (e) {
          developer.log('⚠️ 重置RefreshController状态失败: $e');
        }
      }
    } catch (e) {
      developer.log('💥 加载真实评论数据异常: $e');
      // 发生异常时，保留原有的模拟数据
    } finally {
      isLoadingComments.value = false;
    }
  }

  /// 刷新评论数据（下拉刷新用）
  Future<void> refreshCommentData() async {
    try {
      isRefreshingComments.value = true;
      
      // 🔥 重置分页参数和加载状态，确保后续可以正常上拉加载
      commentCurrentPage = 1;
      hasMoreComments.value = true;

      final response = await CommentApi.getNearbyComments(
        latitude: defaultLatitude,
        longitude: defaultLongitude,
        radius: defaultRadius,
        limit: 20,
      );

      if (response.isSuccess) {
        final realCommentPosts = response.data.map((commentData) => 
          _convertCommentDataToPostModel(commentData)).toList();
        
        // 🔥 使用去重方法处理数据
        _addUniqueComments(realCommentPosts, isRefresh: true);
        
        // 🎯 按时间排序，确保新发布的评论在第一位
        _sortCommentsByTime();
        
        // 🔥 重置RefreshController状态，确保上拉加载功能正常
        try {
          if (commentRefreshController.footerStatus != LoadStatus.idle) {
            commentRefreshController.resetNoData();
          }
          developer.log('🔄 评论RefreshController状态已重置');
        } catch (e) {
          developer.log('⚠️ 重置RefreshController状态失败: $e');
        }
      } else {
        developer.log('❌ 获取评论数据失败');
      }
    } catch (e) {
      developer.log('💥 刷新评论数据异常: $e');
    } finally {
      isRefreshingComments.value = false;
    }
  }

  /// 🔄 评论下拉刷新
  Future<void> onCommentRefresh() async {
    // 🔥 防抖处理：取消之前的定时器
    _commentDebounceTimer?.cancel();
    
    try {
      // 重置分页参数
      commentCurrentPage = 1;
      hasMoreComments.value = true;
      
      await loadCommentData(isRefresh: true);
      
      commentRefreshController.refreshCompleted();
      
    } catch (e) {
      commentRefreshController.refreshFailed();
      developer.log('💥 评论刷新失败: $e');
    }
  }

  /// ⬆️ 评论上拉加载更多
  Future<void> onCommentLoading() async {
    // 🔥 防抖处理：防止重复加载
    if (isLoadingComments.value) {
      developer.log('⚠️ 评论正在加载中，跳过重复请求');
      return;
    }
    
    try {
      if (!hasMoreComments.value) {
        commentRefreshController.loadNoData();
        return;
      }
      
      commentCurrentPage++;
      
      await loadCommentData(isRefresh: false);
      
      if (hasMoreComments.value) {
        commentRefreshController.loadComplete();
      } else {
        commentRefreshController.loadNoData();
      }
      
    } catch (e) {
      commentCurrentPage--; // 失败时回退页码
      commentRefreshController.loadFailed();
      developer.log('💥 评论加载失败: $e');
    }
  }

  /// 📡 通用评论数据加载方法
  Future<void> loadCommentData({required bool isRefresh}) async {
    try {
      if (isRefresh) {
        isLoadingComments.value = true;
      }
      

      
      final response = await CommentApi.getNearbyComments(
        latitude: defaultLatitude,
        longitude: defaultLongitude,
        radius: defaultRadius,
        limit: commentPageSize,
        page: commentCurrentPage, // 🔥 添加分页参数
      );

      if (response.isSuccess) {

        
        // 将CommentData转换为PostModel
        final realCommentPosts = response.data.map((commentData) => 
          _convertCommentDataToPostModel(commentData)).toList();
        
        // 🔥 使用去重方法处理数据
        _addUniqueComments(realCommentPosts, isRefresh: isRefresh);
        
        // 🎯 每次加载后都进行时间排序，确保最新评论在顶部
        _sortCommentsByTime();
        
        // 🔍 检查是否还有更多数据 - 修复逻辑
        final currentPageSize = realCommentPosts.length;
        hasMoreComments.value = currentPageSize >= commentPageSize;
        
        // 如果当前页返回的数据少于pageSize，说明没有更多数据了
        if (currentPageSize < commentPageSize) {
          hasMoreComments.value = false;

        }
        

      } else {


      }
    } catch (e) {


    } finally {
      if (isRefresh) {
        isLoadingComments.value = false;
      }
    }
  }

  /// 将CommentData转换为PostModel
  PostModel _convertCommentDataToPostModel(CommentData commentData) {
    return PostModel(
      id: 'real_comment_${commentData.commentId}',
      title: commentData.commentTitle.isNotEmpty 
          ? commentData.commentTitle 
          : '评论标题',
      content: commentData.commentContent.isNotEmpty 
          ? commentData.commentContent 
          : '暂无内容',
      authorName: commentData.publisherNickname.isNotEmpty 
          ? commentData.publisherNickname 
          : '未知用户',
      authorAvatar: commentData.publisherAvatar, // 🔥 修复：直接使用发布者头像，不使用默认头像
      authorSignature: commentData.publisherSignature.isNotEmpty 
          ? commentData.publisherSignature 
          : '这个人很懒，什么都没留下',
      // 主要图片使用commentImages
      images: commentData.commentImages.isNotEmpty 
          ? commentData.commentImages 
          : [artWorkUrls[commentData.commentId % artWorkUrls.length]], // 如果没有图片，使用默认图片
      // 购物小票使用shoppingImages
      shoppingImages: commentData.shoppingImages.isNotEmpty
          ? commentData.shoppingImages
          : [], // 如果没有购物小票图片，使用空数组
      likeCount: commentData.likeCount,
      commentCount: commentData.commentCount,
      timeAgo: _getTimeAgoText(commentData.minutesAgo),
      type: PostType.comment,
      paymentType: '', // 评论不需要支付方式
      originalCommentId: commentData.commentId, // 🔥 保存原始评论ID
      authorId: commentData.publisherId, // 🔥 添加发布者ID
      publishTime: commentData.commentPublishTime, // 🔥 保存发布时间用于排序
      timestamp: commentData.minutesAgo, // 🔥 保存分钟数用于排序
    );
  }

  /// 根据分钟数获取时间描述
  String _getTimeAgoText(int minutesAgo) {
    if (minutesAgo < 1) return '刚刚';
    if (minutesAgo < 60) return '${minutesAgo}分钟前';
    if (minutesAgo < 1440) return '${(minutesAgo / 60).floor()}小时前';
    return '${(minutesAgo / 1440).floor()}天前';
  }

  /// 获取用户发布的内容
  Future<void> loadUserContent() async {
    if (isLoadingUserContent.value) return;
    
    try {
      isLoadingUserContent.value = true;
      
      developer.log('🔄 开始加载用户发布内容，用户ID: ${currentUserId.value}');

      final response = await UserApi.getUserContent(
        userId: currentUserId.value,
        days: 365, // 🗓️ 查询最近一年的数据
      );

      if (response.isSuccess) {
        developer.log('✅ 用户内容加载成功');
        developer.log('📝 活动数量: ${response.activities.length}');
        developer.log('📝 已结束活动数量: ${response.endedActivities.length}');
        developer.log('📝 评论数量: ${response.comments.length}');
        developer.log('📝 参与活动数量: ${response.participatedActivities.length}');
        developer.log('📊 统计信息: ${response.contentStats}');
        
        // 更新数据
        myActivities.clear();
        myActivities.addAll(response.activities);
        
        myEndedActivities.clear();
        myEndedActivities.addAll(response.endedActivities);
        
        myComments.clear();
        myComments.addAll(response.comments);
        
        // 同时更新真实数据用于UI显示
        myRealComments.clear();
        myRealComments.addAll(response.comments);
        
        myParticipatedActivities.clear();
        myParticipatedActivities.addAll(response.participatedActivities);
        
        // 如果有真实数据，更新历史活动数据（用于"我的发布"页面显示）
        final allActivities = [...response.activities, ...response.endedActivities];
        if (allActivities.isNotEmpty) {
          _updateHistoricalActivityPostsFromAPI(allActivities);
        }
        
        developer.log('✅ 用户内容数据更新完成');
      } else {
        developer.log('❌ 用户内容加载失败: ${response.message ?? "未知错误"}');
        // 失败时保留模拟数据
      }
    } catch (e) {
      developer.log('💥 用户内容加载异常: $e');
      // 异常时保留模拟数据
    } finally {
      isLoadingUserContent.value = false;
    }
  }

  /// 从API数据更新历史活动数据（用于"我的发布"页面）
  void _updateHistoricalActivityPostsFromAPI(List<ActivityData> allActivities) {
    try {
      developer.log('🔄 从API数据更新历史活动列表');
      
      historicalActivityPosts.clear();
      
      // 取前几个活动用于展示
      final displayActivities = allActivities.take(5).toList();
      
      for (int i = 0; i < displayActivities.length; i++) {
        final activity = displayActivities[i];
        
        historicalActivityPosts.add(
          PostModel(
            id: 'api_activity_${activity.activityId}',
            title: activity.activityTitle.isNotEmpty ? activity.activityTitle : '活动标题',
            content: activity.activityDetails.isNotEmpty ? activity.activityDetails : '活动详情',
            images: activity.activityImages.isNotEmpty 
                ? activity.activityImages 
                : [artWorkUrls[i % artWorkUrls.length]],
            shoppingImages: [],
            commentCount: activity.activityCurrentParticipants, // 使用参与人数作为评论数
            paymentType: _getPaymentTypeFromActivityType(activity.activityType),
            type: PostType.myPublish,
            authorName: activity.publisherNickname,
            authorAvatar: activity.publisherAvatar, // 🔥 修复：直接使用发布者头像，不使用默认头像
            authorSignature: activity.publisherSignature.isNotEmpty 
                ? activity.publisherSignature 
                : '来玩真的，不花假的',
            likeCount: 0,
            timeAgo: '${activity.activityCurrentParticipants}/${activity.activityMaxParticipants}',
            activityPublishTime: activity.activityPublishTime, // 🔥 设置真实的活动开始时间（与MyApplication2一致）
            publishTime: activity.activityPublishTime, // 🔥 保持兼容性
            extraData: null, // 🔥 历史活动数据暂时不包含extraData
            // 🎯 活动专用字段
            maxParticipants: activity.activityMaxParticipants,
            currentParticipants: activity.activityCurrentParticipants,
            location: activity.activityLocation,
            latitude: activity.latitude,
            longitude: activity.longitude,
            authorId: activity.publisherId,
          ),
        );
      }
      
      developer.log('✅ 历史活动数据更新完成，共${historicalActivityPosts.length}个活动');
    } catch (e) {
      developer.log('💥 更新历史活动数据异常: $e');
    }
  }

  // ===== 事件通知系统 =====
  // 发布成功事件流
  final RxString _lastPublishEvent = ''.obs;
  
  /// 发送发布成功事件
  void notifyPublishSuccess(String type) {
    _lastPublishEvent.value = type;
    developer.log('🎉 发布成功事件: $type');
    
    // 根据类型自动刷新对应数据
    if (type == 'comment') {
      Future.delayed(Duration(milliseconds: 500), () {
        refreshCommentData(); // 刷新评论数据
        refreshUserContent(); // 刷新用户内容
      });
    } else if (type == 'activity') {
      Future.delayed(Duration(milliseconds: 500), () {
        refreshActivityData(); // 刷新活动数据
        refreshUserContent(); // 刷新用户内容
      });
    }
  }
  
  /// 获取最新发布事件
  String get lastPublishEvent => _lastPublishEvent.value;
  
  /// 清除发布事件
  void clearPublishEvent() {
    _lastPublishEvent.value = '';
  }

  /// 刷新用户发布内容
  Future<void> refreshUserContent() async {
    developer.log('🔄 刷新用户发布内容');
    await loadUserContent();
  }

  /// 获取当前活动的第一个活动数据（用于活动管理卡片显示）
  ActivityData? get currentManagementActivity {
    if (myActivities.isNotEmpty) {
      return myActivities.first;
    }
    return null;
  }

  /// 获取用户内容统计信息
  Map<String, int> get userContentStats => {
    'activeActivities': myActivities.length,
    'endedActivities': myEndedActivities.length,
    'totalActivities': myActivities.length + myEndedActivities.length,
    'comments': myComments.length,
  };

  /// 检查是否有用户内容
  bool get hasUserContent => 
      myActivities.isNotEmpty || 
      myEndedActivities.isNotEmpty || 
      myComments.isNotEmpty;

  // ===== 用户内容相关属性（真实数据） =====
  // 我的评论数据（UserComment格式，从API获取）
  final RxList<UserComment> myRealComments = <UserComment>[].obs;
  
  // 我参与的活动数据（UserParticipatedActivity格式，从API获取）
  final RxList<UserParticipatedActivity> myParticipatedActivities = <UserParticipatedActivity>[].obs;

  /// 编辑活动
  /// [activityId] 活动ID
  /// [activityTitle] 新的活动标题
  /// [activityDetails] 新的活动详情
  /// [activityImages] 新的活动图片列表
  /// [activityType] 新的活动类型
  /// [activityMaxParticipants] 新的最大参与人数
  Future<bool> editActivity({
    required int activityId,
    String? activityTitle,
    String? activityDetails,
    List<String>? activityImages,
    List<String>? activityType,
    int? activityMaxParticipants,
  }) async {
    try {
      developer.log('🔄 控制器开始编辑活动，ID: $activityId');
      
      final response = await ActivityApi.editActivity(
        activityId: activityId,
        activityTitle: activityTitle,
        activityDetails: activityDetails,
        activityImages: activityImages,
        activityType: activityType,
        activityMaxParticipants: activityMaxParticipants,
      );

      if (response.isSuccess) {
        developer.log('✅ 活动编辑成功，开始刷新数据');
        
        // 编辑成功后刷新用户发布的内容
        await refreshUserContent();
        
        developer.log('✅ 用户内容刷新完成');
        return true;
      } else {
        developer.log('❌ 活动编辑失败: ${response.message}');
        return false;
      }
    } catch (e) {
      developer.log('💥 编辑活动异常: $e');
      return false;
    }
  }

  /// 根据活动ID获取活动数据
  ActivityData? getActivityById(int activityId) {
    try {
      return myActivities.firstWhere((activity) => activity.activityId == activityId);
    } catch (e) {
      // 如果没找到，尝试在已结束的活动中查找
      try {
        return myEndedActivities.firstWhere((activity) => activity.activityId == activityId);
      } catch (e) {
        developer.log('⚠️ 未找到ID为 $activityId 的活动');
        return null;
      }
    }
  }

  /// 获取用户完整内容（包括评论和参与的活动）
  Future<void> loadUserFullContent() async {
    try {
      isLoadingUserContent.value = true;
      developer.log('🔄 开始加载用户完整内容（评论+参与活动）');

      // 🔑 使用真实的当前用户ID
      final userId = currentUserId.value;
      
      if (userId == 0) {
        developer.log('⚠️ 用户未登录，无法加载用户内容');
        return;
      }

      // 🗓️ 调用UserApi获取用户内容，查询最近一年的数据
      final response = await UserApi.getUserContent(
        userId: userId,
        days: 365, // 🗓️ 查询最近一年的数据
      );
      
      if (response.isSuccess) {
        // 检查是否已定义myRealComments和myParticipatedActivities，如果没有就先声明
        developer.log('✅ 用户完整内容加载成功');
        developer.log('📝 活动数量: ${response.activities.length}');
        developer.log('📝 已结束活动数量: ${response.endedActivities.length}');
        developer.log('📝 评论数量: ${response.comments.length}');
        developer.log('📝 参与活动数量: ${response.participatedActivities.length}');
        
        // 更新我的评论数据
        myComments.value = response.comments;
        myRealComments.value = response.comments; // 同时更新真实评论数据
        developer.log('✅ 我的评论数据更新完成，数量: ${myComments.length}');
        
        // 更新我的参与活动数据
        myParticipatedActivities.value = response.participatedActivities;
        developer.log('✅ 我的参与活动数据更新完成，数量: ${myParticipatedActivities.length}');
        
        // 更新活动数据
        myActivities.value = response.activities;
        myEndedActivities.value = response.endedActivities;
        developer.log('✅ 我发布的活动数据已更新：活动${response.activities.length}个，已结束${response.endedActivities.length}个');
        
      } else {
        developer.log('❌ 获取用户内容失败: ${response.message ?? "未知错误"}');
      }
      
    } catch (e) {
      developer.log('💥 获取用户内容异常: $e');
    } finally {
      isLoadingUserContent.value = false;
    }
  }





  // 切换标签 - 同步TabController和PageController
  void changeTab(int index) {
    currentTabIndex.value = index;
    // 同步TabController
    tabController.animateTo(index);
    // 同步PageController
    pageController.animateToPage(
      index,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
    
    // 🔄 根据切换的标签获取最新数据
    _refreshDataForTab(index);
    
    // 通知UI更新，确保状态栏样式正确应用
    update(["plays"]);
  }
  
  /// 切换到指定tab索引（别名方法，用于发布成功后跳转）
  void changeTabIndex(int index) {
    changeTab(index);
  }
  
  // ===== 时间排序方法 =====
  
  /// 🎯 按时间排序活动列表（最新的在前）
  void _sortActivitiesByTime() {
    try {
      activityPosts.sort((a, b) {
        // 尝试获取时间戳或日期字符串进行比较
        DateTime? timeA = _parsePostTime(a);
        DateTime? timeB = _parsePostTime(b);
        
        if (timeA == null && timeB == null) return 0;
        if (timeA == null) return 1;
        if (timeB == null) return -1;
        
        // 倒序排列：最新的在前
        return timeB.compareTo(timeA);
      });
      
      developer.log('✅ 活动列表已按时间倒序排列');
    } catch (e) {
      developer.log('❌ 活动时间排序失败: $e');
    }
  }
  
  /// 🎯 按时间排序评论列表（最新的在前）
  void _sortCommentsByTime() {
    try {
      // 排序前记录前几条评论的信息
      if (commentPosts.isNotEmpty) {
        developer.log('🔍 排序前评论顺序:');
        for (int i = 0; i < commentPosts.length && i < 3; i++) {
          final post = commentPosts[i];
          final time = _parsePostTime(post);
          developer.log('  ${i + 1}. ID: ${post.id}, 时间: $time, publishTime: ${post.publishTime}, timestamp: ${post.timestamp}');
        }
      }
      
      commentPosts.sort((a, b) {
        // 尝试获取时间戳或日期字符串进行比较
        DateTime? timeA = _parsePostTime(a);
        DateTime? timeB = _parsePostTime(b);
        
        if (timeA == null && timeB == null) return 0;
        if (timeA == null) return 1;
        if (timeB == null) return -1;
        
        // 倒序排列：最新的在前
        return timeB.compareTo(timeA);
      });
      
      // 排序后记录前几条评论的信息
      if (commentPosts.isNotEmpty) {
        developer.log('🎯 排序后评论顺序:');
        for (int i = 0; i < commentPosts.length && i < 3; i++) {
          final post = commentPosts[i];
          final time = _parsePostTime(post);
          developer.log('  ${i + 1}. ID: ${post.id}, 时间: $time, publishTime: ${post.publishTime}, timestamp: ${post.timestamp}');
        }
      }
      
      developer.log('✅ 评论列表已按时间倒序排列，共${commentPosts.length}条评论');
    } catch (e) {
      developer.log('❌ 评论时间排序失败: $e');
    }
  }
  
  /// 🕒 解析帖子的时间信息
  DateTime? _parsePostTime(dynamic post) {
    try {
      // 🔥 优先使用activityPublishTime字段（与MyApplication2一致）
      if (post.activityPublishTime != null && post.activityPublishTime is String) {
        final parsedTime = DateTime.tryParse(post.activityPublishTime);
        if (parsedTime != null) {
          return parsedTime;
        }
      }
      
      // 🔥 兼容：使用publishTime字段（ISO 8601格式）
      if (post.publishTime != null && post.publishTime is String) {
        final parsedTime = DateTime.tryParse(post.publishTime);
        if (parsedTime != null) {
          return parsedTime;
        }
      }
      
      // 🔥 使用timestamp字段作为minutes_ago计算时间
      if (post.timestamp != null && post.timestamp is int) {
        // timestamp 是minutes_ago，计算实际时间
        final minutesAgo = post.timestamp as int;
        return DateTime.now().subtract(Duration(minutes: minutesAgo));
      }
      
      // 🔥 尝试其他时间字段
      if (post.timestamp != null && post.timestamp is String) {
        // 尝试解析字符串形式的时间戳
        final parsed = int.tryParse(post.timestamp);
        if (parsed != null) {
          if (parsed > 1000000000) {
            // 如果是秒级时间戳
            return DateTime.fromMillisecondsSinceEpoch(parsed * 1000);
          } else {
            // 如果是minutes_ago
            return DateTime.now().subtract(Duration(minutes: parsed));
          }
        }
      }
      
      if (post.time != null && post.time is String) {
        return DateTime.tryParse(post.time);
      }
      
      if (post.createdAt != null && post.createdAt is String) {
        return DateTime.tryParse(post.createdAt);
      }
      
      // 如果都没有，返回当前时间（这样会排在最后）
      return DateTime.now();
    } catch (e) {
      developer.log('⚠️ 解析帖子时间失败: $e');
      return DateTime.now();
    }
  }

  /// 🔄 根据标签索引刷新对应的数据
  void _refreshDataForTab(int tabIndex) {
    developer.log('🔄 切换到标签 $tabIndex，开始刷新数据');
    
    switch (tabIndex) {
      case 0: // 评论标签
        developer.log('📝 刷新评论数据');
        loadRealCommentData();
        break;
      case 1: // 活动标签
        developer.log('🎯 刷新活动数据');
        loadRealActivityData();
        break;
      case 2: // 我的发布标签
        developer.log('📋 刷新用户发布内容');
        loadUserFullContent();
        break;
      default:
        developer.log('⚠️ 未知标签索引: $tabIndex');
        break;
    }
  }

  // ===== 我的发布页面相关刷新方法 =====
  
  /// 🔄 我的历史活动下拉刷新
  Future<void> onMyHistoryRefresh() async {
    try {
      developer.log('🔄 开始刷新我的历史活动');
      
      await loadUserContent(); // 重新加载用户内容
      
      myHistoryRefreshController.refreshCompleted();
      developer.log('✅ 我的历史活动刷新完成');
    } catch (e) {
      developer.log('❌ 我的历史活动刷新失败: $e');
      myHistoryRefreshController.refreshFailed();
    }
  }
  
  /// 🔄 我的评论下拉刷新
  Future<void> onMyCommentsRefresh() async {
    try {
      developer.log('🔄 开始刷新我的评论');
      
      await loadUserFullContent(); // 重新加载用户完整内容
      
      myCommentsRefreshController.refreshCompleted();
      developer.log('✅ 我的评论刷新完成');
    } catch (e) {
      developer.log('❌ 我的评论刷新失败: $e');
      myCommentsRefreshController.refreshFailed();
    }
  }
  
  /// 🔄 我的参与下拉刷新
  Future<void> onMyParticipationRefresh() async {
    try {
      developer.log('🔄 开始刷新我的参与');
      
      await loadUserFullContent(); // 重新加载用户完整内容
      
      myParticipationRefreshController.refreshCompleted();
      developer.log('✅ 我的参与刷新完成');
    } catch (e) {
      developer.log('❌ 我的参与刷新失败: $e');
      myParticipationRefreshController.refreshFailed();
    }
  }
  
  /// 🔄 活动管理下拉刷新
  Future<void> onActivityManagementRefresh() async {
    try {
      developer.log('🔄 开始刷新活动管理');
      
      await loadUserContent(); // 重新加载用户内容，包括活动管理数据
      
      activityManagementRefreshController.refreshCompleted();
      developer.log('✅ 活动管理刷新完成');
    } catch (e) {
      developer.log('❌ 活动管理刷新失败: $e');
      activityManagementRefreshController.refreshFailed();
    }
  }

  void onTap() {}

  @override
  void onInit() {
    super.onInit();
    
    // 🔑 初始化用户ID
    _initializeUserId();
    
    tabController = TabController(length: tabNames.length, vsync: this);
    pageController = PageController(initialPage: 0);

    // 初始化刷新控制器
    activityRefreshController = RefreshController(initialRefresh: false);
    commentRefreshController = RefreshController(initialRefresh: false);
    
    // 初始化我的发布页面相关刷新控制器
    myHistoryRefreshController = RefreshController(initialRefresh: false);
    myCommentsRefreshController = RefreshController(initialRefresh: false);
    myParticipationRefreshController = RefreshController(initialRefresh: false);
    activityManagementRefreshController = RefreshController(initialRefresh: false);

    // Listen to tab changes for background color updates
    tabController.addListener(() {
      if (!tabController.indexIsChanging) {
        currentTabIndex.value = tabController.index;
      }
    });
    
    // 🔄 设置用户状态监听器
    _setupUserListener();
  }
  
  /// 🔑 初始化当前用户ID
  void _initializeUserId() {
    try {
      final userService = UserService.to;
      if (userService.isLoggedIn && userService.currentUser != null) {
        currentUserId.value = userService.currentUser!.userid;
        developer.log('✅ PlaysController获取用户ID: ${currentUserId.value} (${userService.currentUser!.username})', name: 'Plays');
      } else {
        currentUserId.value = 0;
        developer.log('⚠️ PlaysController：用户未登录，使用默认ID: 0', name: 'Plays');
      }
    } catch (e) {
      developer.log('💥 PlaysController初始化用户ID失败: $e', name: 'Plays');
      currentUserId.value = 0;
    }
  }
  
  /// 🔄 设置用户状态监听器
  void _setupUserListener() {
    try {
      // 🔄 定期检查用户状态变化
      Future.doWhile(() async {
        await Future.delayed(const Duration(seconds: 5)); // 每5秒检查一次
        
        final userService = UserService.to;
        int expectedUserId = 0;
        
        if (userService.isLoggedIn && userService.currentUser != null) {
          expectedUserId = userService.currentUser!.userid;
        }
        
        if (currentUserId.value != expectedUserId) {
          currentUserId.value = expectedUserId;
          developer.log('🔄 PlaysController同步用户ID: $expectedUserId', name: 'Plays');
          
          // 🔄 用户状态变化后，重新加载数据
          _initData();
        }
        
        return true; // 继续循环
      });
      
      developer.log('✅ PlaysController用户状态监听器设置成功', name: 'Plays');
    } catch (e) {
      developer.log('💥 PlaysController用户状态监听器设置失败: $e', name: 'Plays');
    }
  }

  @override
  void onReady() {
    super.onReady();
    _initData();

  }
  



  @override
  void onClose() {
    tabController.dispose();
    pageController.dispose();
    
    // 🔥 清理防抖定时器
    _activityDebounceTimer?.cancel();
    _commentDebounceTimer?.cancel();
    
    // 释放刷新控制器
    activityRefreshController.dispose();
    commentRefreshController.dispose();
    
    // 释放我的发布页面相关刷新控制器
    myHistoryRefreshController.dispose();
    myCommentsRefreshController.dispose();
    myParticipationRefreshController.dispose();
    activityManagementRefreshController.dispose();
    
    super.onClose();
  }
}
